package org.terramagnet.mvcframework.query;

import javax.annotation.Resource;
import org.springframework.core.convert.ConversionService;
import org.springframework.util.MultiValueMap;
import org.terramagnet.mvcframework.tools.SpringMvcUtils;

/**
 * 查询条件.
 *
 * <p>
 * 需要配置{@link ConversionService}：</p>
 * <pre><code>&lt;bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"/&gt;</code></pre>
 *
 * @author lip
 */
public class QueryHolder {

    private String sessionKey = "query";

    @Resource
    private ConversionService conversionService;

    /**
     * 保存查询条件.
     *
     * @param namespace 查询所属模块命名空间.
     * @param params 包含查询条件的输入参数
     */
    public void saveRequestParameters(String namespace, MultiValueMap<String, String> params) {
        Query query = new Query();
        query.setConversionService(conversionService);
        query.setRoot(params);
        SpringMvcUtils.setSessionAttribute(namespace + ".query", query);
    }

    public Query query(String namespace) {
        Query query = SpringMvcUtils.getSessionAttribute(namespace + ".query");
        if (query == null) {
            query = new Query();
            query.setConversionService(conversionService);
            SpringMvcUtils.setSessionAttribute(namespace + ".query", query);
        }
        SpringMvcUtils.setSessionAttribute(sessionKey, query.expose());
        return query;
    }

    public void setConversionService(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    /**
     * 设置快速访问的session key.
     */
    public void setSessionKey(String sessionKey) {
        this.sessionKey = sessionKey;
    }
}
